package com.tanhua.server.service;

import com.aliyuncs.utils.StringUtils;
import com.tanhua.commons.exception.TanHuaException;
import com.tanhua.commons.templates.OssTemplate;

import com.tanhua.domain.db.UserInfo;
import com.tanhua.domain.mongo.Voice;
import com.tanhua.dubbo.api.db.UserInfoApi;
import com.tanhua.dubbo.api.mongo.VoiceApi;
import com.tanhua.server.interceptor.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.text.ParseException;


/**
 * @Author Jyz
 * @Date 2021/8/22 - 20:05
 * @Description com.tanhua.server.service
 * @Since version-11
 */
@Service
@Slf4j
public class SendService {

    //语音操作Api
    @Reference
    private VoiceApi voiceApi;
    //阿里云api
    @Autowired
    private OssTemplate ossTemplate;
    //用户详细信息api
    @Autowired
    private UserInfoApi userInfoApi;
    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    /**
     * 发送语音
     * @param soundFile
     * @throws IOException
     */
    public void sendListen(MultipartFile soundFile) throws IOException, ParseException {
        //获得当前用户的id
        Long currentUserId = UserHolder.getUserId();
        //定义次数为3 ,redis查询key
        Integer voice_num=3;
        String key = "SEND_NUM_"+currentUserId;
        String redisValue =redisTemplate.opsForValue().get(key);
        //判断num是否为空(第一次肯定是空)
        if(!StringUtils.isEmpty(redisValue)){
            voice_num= Integer.parseInt(redisValue);// ==>int i = Integer.parseInt(num);  voice_num =i;
        }
        if(voice_num>0){
            //上传语音到阿里云,获取url
            String soundFileUrl = ossTemplate.upload(soundFile.getOriginalFilename(), soundFile.getInputStream());
            //1.封装对象操作
            Voice voice = new Voice();
            //获取当前日期的Long类型
            voice.setCreated(System.currentTimeMillis());
            voice.setUserId(currentUserId);
            voice.setVoiceUrl(soundFileUrl);
            //执行操作前先num--;
            voice_num--;
            //2.redis操作
            //访问时间记录到redis
            redisTemplate.opsForValue().set(key,voice_num+"");
            //根据当前用户id查询用户性别
            UserInfo userInfo = userInfoApi.queryUserInfo(currentUserId);
            //设置用户性别到语音对象
            voice.setGender(userInfo.getGender());
            voiceApi.save(voice);
        }
        else{
            throw new TanHuaException("三次啦,别撒网啦");
        }
    }
}
